package com.test.one.springboottestpne.controller;


import com.alibaba.fastjson.JSON;
import com.test.one.springboottestpne.entity.Resource;
import com.test.one.springboottestpne.entity.User;
import com.test.one.springboottestpne.service.ResourceService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 功能描述：vue 后台测试类
 * 作者：zl
 * 创建时间：2018-10-15
 * 2018年10月15日09:12:38
 */
@RestController
public class ResourceController {


    @Autowired
    ResourceService resourceService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @RequestMapping(value = "/getResourceByLoginName",method = RequestMethod.GET)
    public Map<String,Object> getResourceByLoginName(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws IOException {

        Cookie[] cookies = request.getCookies();
        String id = "";
        for (Cookie cookies1:cookies){
            if ("user".equals(cookies1.getName())){
                id = cookies1.getValue();
                break;
            }
        }
        Map<String,Object> map = new HashMap<>();
        if (StringUtils.isBlank(id)){
            map.put("code","10005");
            map.put("msg","登录失效，重新登录");
            return map;
        }
        String s = stringRedisTemplate.opsForValue().get(id);
        if (StringUtils.isBlank(s)){
            map.put("code","10005");
            map.put("msg","登录失效，重新登录");
            return map;
        }

        User user = JSON.parseObject(s,User.class);

        List<Resource> resourceByLoginName = resourceService.findResourceByLoginName(user.getLoginName());

        List<Resource> resources = new ArrayList<>();
        for(Resource resource:resourceByLoginName){
            if (resource.getPid()==null || resource.getPid().longValue()==0){
                resources.add(resource);
            }
        }

        map.put("code","10000");
        map.put("msg","相应成功");
        map.put("data",resourceByLoginName);
        map.put("pidData",resources);
        return map;
    }
}
